import { useEffect } from "react";
import { Space, Divider, Table, Avatar, Tag, Form, Input, Popconfirm } from "antd";
import { ButtonGroup, Card as SemiCard, Button } from "@douyinfe/semi-ui";
import { useModel } from "umi";
import { useReactive } from "ahooks";
import { IconDelete, IconEdit, IconPlusCircle, IconRefresh } from "@douyinfe/semi-icons";
import { message } from "antd";

import useGatewayType from "../../hooks/resource/useGatewayType";

const { Column } = Table;

const GatewayTypePage = () => {
    const { windowInnerHeight } = useModel("global");
    const { setModalVisible, setModalTitle, setModalWidth, setModalComponent } = useModel("global.modal");
    const { dataLoading, loadGatewayTypes, gatewayTypes } = useGatewayType();
    const { submitLoading, deleteGatewayType } = useGatewayType();
    const { submitLoading: updateLoading, updateIsStop } = useGatewayType();

    const state = useReactive({
        loading: false,
        submitLoading: false,
        types: [],
    });

    const openAddModal = () => {
        setModalTitle("添加组织网关类型");
        setModalVisible(true);
        setModalWidth(500);
        setModalComponent(<Add reloadData={loadGatewayTypes} />);
    };

    const openEditModal = (record) => {
        setModalTitle("编辑组织网关类型信息");
        setModalVisible(true);
        setModalWidth(500);
        setModalComponent(<Edit reloadData={loadGatewayTypes} record={record} />);
    };

    const handleIsStop = async (record) => {
        updateIsStop(record.name, !record.isStop, (res) => {
            if (res) {
                message.success("成功添加组织网关类型信息");
                loadGatewayTypes();
            }
        });
    };

    const handleDelete = async (record) => {
        if (record.isSystem) return message.warning("是系统默认，不能删除");
        deleteGatewayType(record.name, (res) => {
            if (res) {
                message.success("成功添加组织网关类型信息");
                loadGatewayTypes();
            }
        });
    };

    const renderIsStop = (_, r, i) => (
        <Popconfirm title="确定要更改组织网关类型停用状态吗?" okButtonProps={{ loading: updateLoading }} placement="topRight" onConfirm={() => handleIsStop(r)}>
            <Button theme="borderless" type={_ ? "danger" : "primary"} disabled={r.isSystem}>
                {_ ? "已停用" : "正常"}
            </Button>
        </Popconfirm>
    );

    const renderState = (_, r, i) => (
        <Button theme="borderless" type={_ ? "primary" : "danger"}>
            {_ ? "已审核" : "待审核"}
        </Button>
    );

    const renderOperate = (_, r, i) => (
        <Space>
            {!r.isSystem && !r.status && <Button theme="borderless" icon={<IconEdit />} onClick={() => openEditModal(r)} />}
            {!r.isSystem && !r.status && (
                <Popconfirm
                    title="确定要删除组织网关类型信息吗?"
                    okButtonProps={{ loading: submitLoading }}
                    placement="topRight"
                    onConfirm={() => handleDelete(r)}
                >
                    <Button theme="borderless" icon={<IconDelete style={{ color: "#E91E63" }} />} />
                </Popconfirm>
            )}
        </Space>
    );

    const cardBodyHeight = windowInnerHeight - 90 - 20 - 54;

    return (
        <div style={{ padding: 10 }}>
            <SemiCard
                title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>组织网关类型</span>}
                headerExtraContent={
                    <ButtonGroup>
                        <Button icon={<IconPlusCircle />} onClick={openAddModal} />
                        <Button icon={<IconRefresh />} onClick={loadGatewayTypes} />
                    </ButtonGroup>
                }
                headerStyle={{ padding: "10px 14px" }}
                shadows="always"
                bordered={false}
                bodyStyle={{ padding: 0, height: cardBodyHeight, overflow: "auto" }}
            >
                <Table
                    loading={dataLoading}
                    dataSource={gatewayTypes}
                    rowKey="name"
                    bordered
                    size="small"
                    pagination={false}
                    scroll={{ y: cardBodyHeight - 40 }}
                >
                    <Column title="序号" align="center" width={60} render={(_, r, i) => i + 1} />
                    <Column title="类型名称" dataIndex="name" align="center" width={160} />
                    <Column title="备注" dataIndex="notes" align="left" />
                    <Column title="提交人" dataIndex="creater" align="center" width={80} render={(_, r, i) => _?.name} />
                    <Column title="提交时间" dataIndex="creater" align="center" width={160} render={(_, r, i) => (_?.time ? formatUTCTime(_.time) : "-")} />
                    <Column title="停用状态" dataIndex="isStop" align="center" width={100} render={renderIsStop} />
                    <Column title="审核状态" dataIndex="status" align="center" width={100} render={renderState} />
                    <Column title="操作" align="center" width={100} render={renderOperate} />
                </Table>
            </SemiCard>
        </div>
    );
};

const Add = ({ reloadData }) => {
    const { onCloseGlobalModal } = useModel("global.modal");
    const [form] = Form.useForm();
    const { submitLoading, insertGatewayType } = useGatewayType();

    const onFinish = async (values) => {
        insertGatewayType(values, (res) => {
            if (res) {
                message.success("成功添加组织网关类型信息");
                reloadData();
                onCloseGlobalModal();
            }
        });
    };

    return (
        <div style={{ padding: 10 }}>
            <Form form={form} onFinish={onFinish} layout="horizontal" labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
                <Form.Item label="类型名称" name="name" rules={[{ required: true, validator: nameValidator }]}>
                    <Input />
                </Form.Item>

                <Form.Item label="备注" name="notes" rules={[{ required: true, validator: notesValidator }]}>
                    <Input />
                </Form.Item>

                <div style={{ textAlign: "center" }}>
                    <Space>
                        <Button loading={submitLoading} type="primary" htmlType="submit">
                            提交
                        </Button>
                        <Button loading={submitLoading} htmlType="button" onClick={() => form.resetFields()}>
                            重置
                        </Button>
                    </Space>
                </div>
            </Form>
        </div>
    );
};

const Edit = ({ record, reloadData }) => {
    const { onCloseGlobalModal } = useModel("global.modal");
    const [form] = Form.useForm();
    const { submitLoading, updateGatewayType } = useGatewayType();

    const onFinish = async (values) => {
        values.name = record.name;
        updateGatewayType(values, (res) => {
            if (res) {
                message.success("成功更新组织网关类型信息");
                reloadData();
                onCloseGlobalModal();
            }
        });
    };

    return (
        <div style={{ padding: 10 }}>
            <Form form={form} onFinish={onFinish} layout="horizontal" labelCol={{ span: 6 }} wrapperCol={{ span: 16 }} initialValues={record}>
                <Form.Item label="备注" name="notes" rules={[{ required: true, validator: notesValidator }]}>
                    <Input />
                </Form.Item>

                <div style={{ textAlign: "center" }}>
                    <Space>
                        <Button loading={submitLoading} type="primary" htmlType="submit">
                            提交
                        </Button>
                        <Button loading={submitLoading} htmlType="button" onClick={() => form.resetFields()}>
                            重置
                        </Button>
                    </Space>
                </div>
            </Form>
        </div>
    );
};

const nameValidator = (rule, value) => {
    if (value && /^[a-z]{1,}$/.test(value)) {
        return Promise.resolve();
    } else {
        return Promise.reject("类型名称只能输入英文小写字母，至少1个字符");
    }
};

const notesValidator = (rule, value) => {
    if (value && validates.textArea(value)) {
        return Promise.resolve();
    } else {
        return Promise.reject("备注含有非法字条");
    }
};

export default GatewayTypePage;
